package com.wisdom.voip;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.hisun.phone.core.voice.CCPCall;
import com.hisun.phone.core.voice.Device;
import com.hisun.phone.core.voice.DeviceListener;
import com.hisun.phone.core.voice.Log4Util;
import com.hisun.phone.core.voice.model.ChatRoomInfo;
import com.hisun.phone.core.voice.model.ChatRoomMember;
import com.hisun.phone.core.voice.model.ChatRoomMsg;
import com.hisun.phone.core.voice.model.InterphoneMember;
import com.hisun.phone.core.voice.model.InterphoneMsg;
import com.hisun.phone.core.voice.model.ReceiveVoiceInfo;
import com.hisun.phone.core.voice.model.UserAgentConfig;
import com.hisun.phone.core.voice.model.VoiceMsgMemeber;
import org.sipdroid.sipua.R;
import com.wisdom.VoiceApplication;
import com.wisdom.tools.CCPConfig;
import com.wisdom.view.SetPwdActivity;
public class VoiceHelper implements CCPCall.InitListener,DeviceListener{
	public static final String WISDOMCALL_TAG="Wisdom_Call";
	private Context context;
	
	private Handler helperHandler;
	
	private NotificationManager mNotificationManager;
	// invoked after created it
		private Device device;
		
		/**
		 * handler 转换消息id
		 */
		public static final int WHAT_ON_CONNECT = 0x2000;
		public static final int WHAT_ON_DISCONNECT = 0x2001;
		public static final int WHAT_ON_CALL_ALERTING = 0x2002;
		public static final int WHAT_ON_CALL_ANSWERED = 0x2003;
		public static final int WHAT_ON_CALL_PAUSED = 0x2004;
		public static final int WHAT_ON_CALL_PAUSED_REMOTE = 0x2005;
		public static final int WHAT_ON_CALL_RELEASED = 0x2006;
		public static final int WHAT_ON_CALL_PROCEEDING = 0x2007;
		public static final int WHAT_ON_CALL_TRANSFERED = 0x2008;
		public static final int WHAT_ON_CALL_MAKECALL_FAILED = 0x2009;
		public static final int WHAT_ON_TEXT_MESSAGE_RECEIVED = 0x201A;
		public static final int WHAT_ON_CALL_BACKING = 0x201B;
		
		//2013.3.11
		public static final int WHAT_ON_NEW_VOICE = 0x201C;
		public static final int WHAT_ON_AMPLITUDE = 0x201D;
		public static final int WHAT_ON_RECODE_TIMEOUT = 0x202A;
		public static final int WHAT_ON_UPLOAD_VOICE_RES = 0x202B;
		public static final int WHAT_ON_PLAY_VOICE_FINSHING = 0x202C;
		
		public static final int WHAT_ON_INTERPHONE = 0x203A;
		public static final int WHAT_ON_CONTROL_MIC = 0x203B;
		public static final int WHAT_ON_RELEASE_MIC = 0x203C;
		public static final int WHAT_ON_INTERPHONE_MEMBERS = 0x203D;
		public static final int WHAT_ON_INTERPHONE_SIP_MESSAGE = 0x203E;
		public static final int WHAT_ON_DIMISS_DIALOG = 0x204A;;
		
		public static final int WHAT_ON_REQUEST_MIC_CONTROL = 0x204C;
		public static final int WHAT_ON_RELESE_MIC_CONTROL = 0x204D;
		public static final int WHAT_ON_PLAY_MUSIC = 0x204E;
		public static final int WHAT_ON_STOP_MUSIC = 0x204F;

		
		public static final int WHAT_ON_VERIFY_CODE_SUCCESS = 0x205A;
		public static final int WHAT_ON_VERIFY_CODE_FAILED = 0x205B;
		
		// ChatRoom
		public static final int WHAT_ON_CHATROOM_SIP_MESSAGE = 0x205C;
		public static final int WHAT_ON_CHATROOM_MEMBERS = 0x205D;
		public static final int WHAT_ON_CHATROOM_LIST = 0x205E;
		public static final int WHAT_ON_CHATROOM = 0x206A;
		public static final int WHAT_ON_CHATROOM_INVITE = 0x206B;
		public static final int WHAT_ON_MIKE_ANIM = 0x206C;
		public static final int WHAT_ON_CNETER_ANIM = 0x206D;
		public static final int WHAT_ON_VERIFY_CODE = 0x206E;
		public static final int WHAT_ON_CHATROOMING = 0x207A;
	public VoiceHelper(Context context,Handler handler){
		this.context=context;
		this.helperHandler=handler;
		this.mNotificationManager=(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
		CCPCall.init(context,this);
		Log4Util.d(WISDOMCALL_TAG,"[VoiceHelper] CCPCallService init");
	}
	/**
	 * get the device.
	 * 
	 * @return the device
	 */
	public Device getDevice() {
		return device;
	}
	long t = 0;
	/**
	 * send object to activity by handler
	 * @param what
	 * 			message id of handler
	 * @param obj
	 * 			message of handler
	 */
	private void sendTarget(int what,Object obj){
		t=System.currentTimeMillis();
		// for kinds of mobile phones
		while(handler==null&&(System.currentTimeMillis()-t<3200)){
			Log4Util.d(WISDOMCALL_TAG,"[VoiceHelper] handler is null, activity maybe destory, wait...");
		}
		try{
			Thread.sleep(80L);
		}catch(InterruptedException e){
			
		}
		if(handler==null){
			Log4Util.d(WISDOMCALL_TAG , "[VoiceHelper] handler is null, need adapter it.");
			return;
		}
		
		Message msg=Message.obtain(handler);
		msg.what=what;
		msg.obj=obj;
		msg.sendToTarget();
	} 
	
	
	@Override
	public void onCallAlerting(String callid) {
		sendTarget(WHAT_ON_CALL_ALERTING, callid);
		
	}

	@Override
	public void onCallAnswered(String callid) {
		sendTarget(WHAT_ON_CALL_ANSWERED, callid);
		
	}

	@Override
	public void onCallBacking(CBState status, String self, String dest) {
		Bundle b=new Bundle();
		b.putSerializable(Device.CBSTATE, status);
		b.putString(Device.SELFPHONE, self);
		b.putString(Device.DESTPHONE, dest);
		sendTarget(WHAT_ON_CALL_BACKING,b);
		
	}

	@Override
	public void onCallPaused(String callid) {
		
		
	}

	@Override
	public void onCallPausedByRemote(String callid) {
		
		
	}

	@Override
	public void onCallProceeding(String callid) {
		sendTarget(WHAT_ON_CALL_PROCEEDING, callid);
		
	}

	@Override
	public void onCallReleased(String callid) {
		sendTarget(WHAT_ON_CALL_RELEASED, callid);
		
	}

	@Override
	public void onCallTransfered(String callid, String destionation) {
		Bundle b=new Bundle();
		b.putString(Device.CALLID, callid);
		b.putString(Device.DESTIONATION, destionation);
		sendTarget(WHAT_ON_CALL_TRANSFERED,b);
		
		
	}

	@Override
	public void onChatRoomInvite(int reason, String confNo) {
		Log4Util.d(WISDOMCALL_TAG , "[onChatRoomInvite ] reason " + reason + " , confNo "  +  confNo);
		Bundle b = new Bundle();
		b.putInt(Device.REASON, reason);
		b.putString(Device.CONFNO, confNo);
		sendTarget(WHAT_ON_CHATROOM_INVITE, b);
		
	}

	@Override
	public void onChatRoomMembers(int reason, List<ChatRoomMember> member) {
		Log4Util.d(WISDOMCALL_TAG , "[onChatRoomMembers ] on Chat Room  members that .. " + member.toString());
		Bundle b = new Bundle();
		b.putSerializable(Device.CHATROOM_MEMBERS, (ArrayList<ChatRoomMember>) member);
		sendTarget(WHAT_ON_CHATROOM_MEMBERS, b);
		
	}

	@Override
	public void onChatRoomState(int reason, String confNo) {
		Log4Util.d(WISDOMCALL_TAG , "[onChatRoomState ] reason " + reason + " , confNo "  +  confNo);
		Bundle b = new Bundle();
		b.putInt(Device.REASON, reason);
		b.putString(Device.CONFNO, confNo);
		sendTarget(WHAT_ON_CHATROOM, b);
		
	}

	@Override
	public void onChatRooms(int reason, List<ChatRoomInfo> chatRoomList) {
		Log4Util.d(WISDOMCALL_TAG , "[onChatrooms ] on Chat Room  chatrooms that .. " + chatRoomList.toString());
		Bundle b = new Bundle();
		b.putSerializable(Device.CHATROOM_LIST, (ArrayList<ChatRoomInfo>) chatRoomList);
		sendTarget(WHAT_ON_CHATROOM_LIST, b);
		
	}

	@Override
	public void onConnected() {
		Message msg = Message.obtain(helperHandler);
		msg.what = WHAT_ON_CONNECT;
		msg.sendToTarget();
		Log4Util.d(WISDOMCALL_TAG , "已经成功连接上云通讯平台");
		
	}

	@Override
	public void onControlMicState(int reason, String speaker) {
		Log4Util.d(WISDOMCALL_TAG , "[onControlMicState ] control mic return  , reason " +reason + " , and speaker " + speaker );
		Bundle b = new Bundle();
		b.putInt(Device.REASON, reason);
		b.putString(Device.SPEAKER, speaker);
		sendTarget(WHAT_ON_CONTROL_MIC, b);
		
	}

	@Override
	public void onDisconnect(Reason reason) {
		Message msg = Message.obtain(helperHandler);
		msg.what = WHAT_ON_DISCONNECT;
		msg.obj = reason;
		msg.sendToTarget();
		Log4Util.d(WISDOMCALL_TAG , "未与云通讯平台进行连接,请重试");
		
	}

	@Override
	public void onDownLoadVoiceMsgs(int reason, String fileName) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onFinishedPlaying() {
		Log4Util.d(WISDOMCALL_TAG , "[onFinishedPlaying ] MediaPlayManager play is stop ..");
		Bundle b = new Bundle();
		sendTarget(WHAT_ON_PLAY_VOICE_FINSHING, b);
		
	}

	@Override
	public void onGetMemberList(int reason, List<VoiceMsgMemeber> mbers) {
		Log4Util.d(WISDOMCALL_TAG , "[onGetMemberList ] reason " + reason + " , mbers count "  +  mbers.size());
		
	}

	@Override
	public void onInterphoneMembers(List<InterphoneMember> member) {
		Log4Util.d(WISDOMCALL_TAG , "[onInterphoneMembers ] on inter phone members that .. " + member.toString());
		Bundle b = new Bundle();
		b.putSerializable(Device.MEMBERS, (ArrayList<InterphoneMember>) member);
		sendTarget(WHAT_ON_INTERPHONE_MEMBERS, b);
		
	}

	@Override
	public void onInterphoneState(int reason, String confNo) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onLogInfo(String info) {
		// TODO: save LogUtil in the file or others
				if(TextUtils.isEmpty(info)){
					return ;
				}
				Log4Util.d(WISDOMCALL_TAG , info);
		
	}

	@Override
	public void onMakeCallFailed(String callid, Reason reason) {
		Bundle b = new Bundle();
		b.putString(Device.CALLID, callid);
		b.putSerializable(Device.REASON, reason);
		sendTarget(WHAT_ON_CALL_MAKECALL_FAILED, b);
		
	}

	@Override
	public void onMessageSendReport(int msgid, ReportState rs) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onNewVoiceMsgs(int reason, int count, List<ReceiveVoiceInfo> rVoiceList) {
		Log4Util.d(WISDOMCALL_TAG , "[onNewVoiceMsgs ] reason " + reason + " , mbers count "  +  count);
		Bundle b = new Bundle();
		b.putInt(Device.REASON , reason);
		b.putString("count" , count + "");
		b.putSerializable("ReceiveVoiceList", (ArrayList<ReceiveVoiceInfo>)rVoiceList);
		sendTarget(WHAT_ON_NEW_VOICE, b);
		
	}

	@Override
	public void onReceiveChatRoomMsg(ChatRoomMsg arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onReceiveInterphoneMsg(InterphoneMsg arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onReceiveVoiceMsg(ReceiveVoiceInfo arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onRecordingAmplitude(double arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onRecordingTimeOut(long arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onReleaseMicState(int reason) {
		Log4Util.d(WISDOMCALL_TAG , "[onReleaseMicState ] on release mic return reason  .. " +reason);
		Bundle b = new Bundle();
		b.putInt(Device.REASON, reason);
		sendTarget(WHAT_ON_RELEASE_MIC, b);
		
	}

	@Override
	public void onTextMessageReceived(String arg0, String arg1) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onUploadVoiceMsg(int arg0, ReceiveVoiceInfo arg1) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void receivePresenceEvents(APN apn, NetworkState ns) {
		
	}

	@Override
	public void onError(Exception exception) {
		Log4Util.d(WISDOMCALL_TAG, "[onError] " + "SDK初始化错误, " + exception.getMessage());
		Message msg=Message.obtain(helperHandler);
		if(exception.getMessage()!=null&&exception.getMessage().equals(context.getString(R.string.ccp_sdk_init_str))){
			onInitialized();
	}else{
		msg.what=SetPwdActivity.WHAT_INIT_ERROR;
		msg.obj= "[onError] " + "SDK初始化错误, " + exception.getMessage();
		msg.sendToTarget();
	}
		
	}

	@Override
	public void onInitialized() {
		try{
			//封装参数
			Map<String,String>params=new HashMap<String,String>();
			//* REST服务器地址
			params.put(UserAgentConfig.KEY_IP,CCPConfig.REST_SERVER_ADDRESS);
			params.put(UserAgentConfig.KEY_PORT,CCPConfig.REST_SERVER_PORT);
			//* VOIP账号 , 可以填入CCP网站Demo管理中的测试VOIP账号信息
			params.put(UserAgentConfig.KEY_SID, CCPConfig.VoIP_ID);
			//* VOIP账号密码, 可以填入CCP网站Demo管理中的测试VOIP账号密码
			params.put(UserAgentConfig.KEY_PWD, CCPConfig.VoIP_PWD);
			//* 子账号, 可以填入CCP网站Demo管理中的测试子账号信息
			params.put(UserAgentConfig.KEY_SUBID, CCPConfig.Sub_Account);
			//* 子账号密码, 可以填入CCP网站Demo管理中的测试子账号密码
			params.put(UserAgentConfig.KEY_SUBPWD, CCPConfig.Sub_Token);
			// User-Agent
			params.put(UserAgentConfig.KEY_UA, VoiceApplication.getInstance().getUser_Agent());
			
			//创建Device
			device=CCPCall.createDevice(this, params);
			
			//设置当呼入请求到达时，唤起的界面
			Intent intent=new Intent(context,CallInActivity.class);
			PendingIntent pendingIntent=PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
			device.setIncomingIntent(pendingIntent);
			
			device.setCodecEnabled(4,false);
			Log4Util.d(WISDOMCALL_TAG , "[onInitialized] sdk init success. finsh...");
		}catch(Exception e){
			e.printStackTrace();
			throw new RuntimeException(e.getMessage());
		}
		
	}
	/**
	 * handler for update activity
	 */
	private Handler handler;

	/**
	 * set handler.
	 * 
	 * @param handler
	 *            activity handler
	 */
	public void setHandler(final Handler handler) {
		this.handler = handler;
	}


}
